﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QuickApp.Core;
using Resto.CostControl.Core;
using Resto.CostControl.Core.DWZAdapter;
using EfSearchModel.Model;

namespace Resto.CostControl.Web.Controllers
{
    public class PriceController : Controller
    {
        private readonly IRepository<MaterialPrice> _Repo;
        private readonly IUnitOfWork _UnitOfWork;

        public PriceController(IRepository<MaterialPrice> repo, UnitOfWork unitOfWork)
        {
            _Repo = repo;
            _UnitOfWork = unitOfWork;
        }

        //
        // GET: /Material/

        public ActionResult Index(DWZPageInfo pageInfo, QueryModel where)
        {
            var list = _Repo.GetPageable(pageInfo, where);

            ViewBag.Total = list.Total;
            ViewBag.PageNum = pageInfo.PageIndex + 1;
            ViewBag.NumPerPage = pageInfo.PageSize;
            ViewBag.OrderField = pageInfo.SortName;
            ViewBag.OrderDirection = pageInfo.SortOrder;
            ViewBag.Keywords = pageInfo.Keywords;
            ViewBag.SearchData = pageInfo.SearchData;

            return View(list.Page);
        }

        public ActionResult Edit(string Id)
        {
            MaterialPrice data = null;
            if (!string.IsNullOrWhiteSpace(Id))
            {
                data = _Repo.Find(Id);
            }
            else
            {
                data = new MaterialPrice();
            }
            return View(data);
        }

        [HttpPost]
        public JsonResult Save(MaterialPrice data)
        {
            if (ModelState.IsValid)
            {
                if (string.IsNullOrWhiteSpace(data.Id))
                {
                    data.Id = Guid.NewGuid().ToString();
                    _Repo.Insert(data);
                }
                else
                {
                    var oldData = _Repo.Find(data.Id);
                    TryUpdateModel(oldData);
                }

                _UnitOfWork.Commit();
            }

            var result = new FormReturnJson
            {
                statusCode = "200",
                message = "操作成功",
                navTabId = "MaterialPrice",
                callbackType = "closeCurrent",
                forwardUrl = "",
            };
            return Json(result);
        }
    }
}